import streamlit as st
import os
import sys
import json
from config import create_directories, VIDEOS_DIR
from video_processor import (
    download_video,
    extract_audio,
    transcribe_audio,
    summarize_transcript
)

# --- 页面配置 ---
st.set_page_config(
    page_title="Bilibili 视频 AI 总结工具",
    page_icon="🎥",
    layout="wide"
)

st.title("Bilibili 视频 AI 总结工具 🎥")
st.markdown("输入一个 Bilibili 视频链接, AI 将自动为您下载视频, 转录内容, 并生成带时间戳的摘要.")

# --- 初始化 --- 
# 创建输出目录
create_directories()

# 在 session state 中初始化变量
if 'processing' not in st.session_state:
    st.session_state.processing = False
if 'summary' not in st.session_state:
    st.session_state.summary = ""
if 'transcript' not in st.session_state:
    st.session_state.transcript = ""
if 'video_path' not in st.session_state:
    st.session_state.video_path = ""

# --- UI 界面 ---
video_url = st.text_input("请输入 Bilibili 视频 URL", placeholder="例如: https://www.bilibili.com/video/BV1xx411c7mD")

if st.button("开始分析", type="primary", use_container_width=True, disabled=st.session_state.processing):
    if video_url:
        st.session_state.processing = True
        # 清空旧数据
        st.session_state.summary = ""
        st.session_state.transcript = ""
        st.session_state.video_path = ""
        
        # 使用 st.empty() 来创建占位符, 以便后续更新状态
        status_placeholder = st.empty()

        try:
            # 流程 1: 下载视频
            status_placeholder.info("Step 1/4: 正在下载视频... 请稍候, 这可能需要一些时间.")
            video_path = download_video(video_url)
            st.session_state.video_path = video_path

            # 流程 2: 提取音频
            status_placeholder.info("Step 2/4: 正在提取音频...")
            audio_path = extract_audio(video_path)

            # 流程 3: 转录音频
            status_placeholder.info("Step 3/4: 正在转录音频... (Whisper 模型加载和处理可能需要几分钟)")
            transcript_path = transcribe_audio(audio_path)
            with open(transcript_path, 'r', encoding='utf-8') as f:
                transcript_data = json.load(f)
                st.session_state.transcript = transcript_data

            # 流程 4: 总结文本
            status_placeholder.info("Step 4/4: 正在生成 AI 摘要...")
            summary_path = summarize_transcript(transcript_path)
            with open(summary_path, 'r', encoding='utf-8') as f:
                st.session_state.summary = f.read()
            
            status_placeholder.success("🎉 分析完成!")

        except Exception as e:
            status_placeholder.error(f"处理失败: {e}")
        finally:
            st.session_state.processing = False
            # 强制 Streamlit 重新运行以更新 UI
            st.rerun()
    else:
        st.warning("请输入有效的视频 URL.")

# --- 结果展示 ---
if st.session_state.video_path and os.path.exists(st.session_state.video_path):
    st.divider()
    col1, col2 = st.columns(2)

    # 添加自定义CSS样式
    st.markdown("""
    <style>
    .video-container {
        max-height: 66.67vh;  /* 限制视频区域最大高度为视口高度的2/3 */
        overflow: hidden;   /* 超出部分隐藏 */
    }
    #video-player {
        width: 100%;      /* 视频宽度占满容器 */
    }
    .timestamp-link {
        color: #1E88E5;   /* 时间戳链接颜色 */
        text-decoration: underline;
        cursor: pointer;
    }
    </style>
    <script>
    // 视频跳转函数
    function seekToVideo(timeString) {
        const video = document.querySelector('video');
        if (video) {
            const parts = timeString.split(':');
            const seconds = parseInt(parts[0]) * 3600 + parseInt(parts[1]) * 60 + parseInt(parts[2]);
            video.currentTime = seconds;
            video.play();
        }
    }
    </script>
    """, unsafe_allow_html=True)

    with col1:
        st.subheader("视频播放器")
        # 使用HTML5视频标签替代原生组件，以便控制ID和样式
        # 使用Streamlit原生视频组件并应用样式
        st.markdown('<div class="video-container">', unsafe_allow_html=True)
        st.video(st.session_state.video_path)
        st.markdown('</div>', unsafe_allow_html=True)

    with col2:
        st.subheader("AI 摘要 (带时间戳)")
        if st.session_state.summary:
            # 处理摘要文本，将时间戳转换为可点击链
            import re
            # 使用Streamlit回调函数实现时间戳跳转
            summary_html = st.session_state.summary
            # 将时间戳转换为可点击链接
            summary_html = re.sub(r'(视频节点: (\d{2}:\d{2}:\d{2}))', 
                               r'<a href="javascript:void(0)" class="timestamp-link" onclick="seekToVideo(\"\2\")">\1</a>', 
                               st.session_state.summary)
            st.markdown(summary_html, unsafe_allow_html=True)
            # 显示处理后的摘要文本
            # 使用re.sub()替换正则匹配内容
            cleaned_summary = re.sub(r'(视频节点: \d{2}:\d{2}:\d{2})', '', summary_html)
            st.markdown(cleaned_summary, unsafe_allow_html=True)
        else:
            st.markdown("摘要生成中...")

    with st.expander("查看完整视频文稿"):
        if st.session_state.transcript:
            # 格式化文稿以提高可读性
            formatted_transcript = ""
            for segment in st.session_state.transcript.get('segments', []):
                start_time = int(segment['start'])
                h, m, s = start_time // 3600, (start_time % 3600) // 60, start_time % 60
                time_str = f"[{h:02d}:{m:02d}:{s:02d}]"
                formatted_transcript += f"**{time_str}** {segment['text']}\n\n"
            st.markdown(formatted_transcript)
        else:
            st.info("完整文稿正在生成中...")